import http from '@/utils/request'
import { getLocalChannels, hasToken, setLocalChannels } from '@/utils/storage'
import { Toast } from 'antd-mobile'
import store, { AppDispatch } from '..'
import { Channels } from '../reducer/channel'

/**
 * 获取用户的频道
 * @returns
 */
export const getUserChannelAPI = () => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      // 情况1: 如果有Token 返回该用户的频道信息
      const res = await http.get('/v1_0/user/channels')
      // console.log('/v1_0/channels', res)
      // 存储到 redux  用于界面渲染
      dispatch({ type: 'channel/savaList', payload: res.data.channels })
    } else {
      // 情况2: 用户未登录, 返回后台设置的默认频道列表(优先获取本地)
      const localList = getLocalChannels()
      if (localList.length) {
        // 情况2.1: 本地有频道数据, 存储到 redux  用于界面渲染
        dispatch({ type: 'channel/savaList', payload: localList })
      } else {
        // 情况2.2 本地没有频道数据, 发送请求,获取默认频道
        const res = await http.get('/v1_0/user/channels')
        // 存储到 redux  用于界面渲染
        dispatch({ type: 'channel/savaList', payload: res.data.channels })
        // 保存到本地
        setLocalChannels(res.data.channels)
      }
    }
  }
}

/**
 * 获取用户的频道
 * @returns
 */
export const getAllChannelAPI = () => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get('/v1_0/channels')
    // 存储到 redux  用于界面渲染
    dispatch({ type: 'channel/savaAllList', payload: res.data.channels })
  }
}

/**
 * 添加用户频道
 * @param item
 * @returns
 */
export const addChannelAPI = (item: Channels) => {
  return async (dispatch: AppDispatch) => {
    // 获取仓库数据
    const { list } = store.getState().channel
    // 合并数据
    const channels = [...list, item]

    if (hasToken()) {
      // 情况1: 有token 发送请求
      await http.patch('/v1_0/user/channels', {
        channels: channels,
      })
    } else {
      // 情况2: 用户未登录, 把数据存储到本地
      setLocalChannels(channels)
    }
    // 存储到 redux  用于界面渲染
    dispatch({ type: 'channel/savaList', payload: channels })
  }
}

/**
 * 删除用户频道列表
 * @param id
 * @returns
 */
export const deleteChannelAPI = (id: number) => {
  return async (dispatch: AppDispatch) => {
    // 获取仓库的用户频道列表
    const { list } = store.getState().channel
    // 过滤掉删除的数据
    const newList = list.filter((item) => {
      if (list.length <= 5) {
        Toast.show({ content: '至少保留5个频道' })
        return item
      } else {
        return item.id !== id
      }
    })
    if (hasToken()) {
      //情况1: 已登录, 发送请求
      await http.delete(`/v1_0/user/channels/${id}`)
    } else {
      // 情况2：未登录，修改本地存储
      setLocalChannels(newList)
    }
    // 存储到 redux  用于界面渲染
    dispatch({ type: 'channel/savaList', payload: newList })
  }
}

/**
 *  选中频道 id
 * @param id
 * @returns
 */
export const changeChannelIdAPI = (id: number) => {
  return (dispatch: AppDispatch) => {
    dispatch({ type: 'channel/changeActiveId', payload: id })
  }
}
